package com.qctpos.crm.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lizz
 * @date: 2020/1/20 09:58
 */
public class JwtTokenUtil {

    // Token请求头
    public static final String TOKEN_HEADER = "Authorization";
    // Token前缀
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 引入apollo的配置
     */
    private static String TOKEN_KEY = "54f12048-1f56-45c1-a3f1-2c546bc2bb42";
    /**
     * jwt有效时间 一天
     */
    private static long TOKEN_TIMEOUT = 1000 * 60 * 60 * 24;

    /**
     * jwt生成方
     */
    private final static String JWT_ISSUER = "qct_pos";

    /**
     * 生成jwt
     *
     * @param header
     * @return
     */
    public static String create(Map<String, Object> header) {
        return create(header, new HashMap<>(0), JWT_ISSUER, TOKEN_TIMEOUT);
    }

    public static String create(Map<String, Object> header, Map<String, String> claims) {
        return create(header, claims, JWT_ISSUER, TOKEN_TIMEOUT);
    }

    public static String create(Map<String, Object> header, long timeout) {
        return create(header, new HashMap<>(0), JWT_ISSUER, timeout);
    }

    /**
     * 生成jwt
     *
     * @param header
     * @param issuer
     * @return
     */
    public static String create(Map<String, Object> header, Map<String, String> claims, String issuer, long timeout) {
        String token;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
            Date date = new Date(System.currentTimeMillis() + timeout);
            JWTCreator.Builder builder = JWT.create()
                    .withHeader(header)
                    .withIssuer(issuer)
                    .withExpiresAt(date);
            for (String key : claims.keySet()) {
                builder.withClaim(key, claims.get(key));
            }
            token = builder.sign(algorithm);
        } catch (JWTVerificationException exception) {
            System.out.println(exception.getMessage());
            return null;
        }
        return token;
    }

    /**
     * 验证jwt
     *
     * @param token
     */
    public static void decode(String token) throws JWTVerificationException {
        // 去掉前缀 获取Token字符串
        token = token.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
        JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(JWT_ISSUER).build();
        verifier.verify(token);
    }
}